import { IEchartsData } from '@/model/echarts/echartsInter'
import { categoryData, dataFlag, markPoint, noSeries, valueMax } from '@/utils/echartsCommonFun'
import {
  BarSeriesOption,
  EChartsOption,
  GridOption,
  TooltipOption,
  XAXisOption,
  YAXisOption
} from 'echarts/types/dist/shared'
import { ItemStyleOption } from 'echarts/types/src/util/types'

export function Chart (datas:IEchartsData) {
  const series = []
  let category:Array<string> = []
  let max = 0
  const flag = dataFlag(datas.data)
  if (flag > 0 && flag === datas.data.length) { // 没有数据
    series.push(noSeries())
  } else {
    datas.data.forEach((data, index) => {
      let value:Array<{
        itemStyle: ItemStyleOption,
        name:string,
        value:number}> = []
      if (data.value) {
        value = data.value.map(item => {
          category = categoryData(category, item.name)
          max = valueMax(max, item.value)
          return {
            name: item.name,
            value: item.value,
            itemStyle: { borderRadius: item.value > 0 ? [15, 15, 0, 0] : [0, 0, 15, 15] } as ItemStyleOption
          }
        })
      }

      series.push({
        name: data.name ? data.name : '',
        type: 'bar',
        data: value,
        barWidth: '30%',
        barMaxWidth: 15,
        smooth: true,
        symbol: 'none',
        markPoint: markPoint(data),
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      } as BarSeriesOption)
    })
  }
  return {
    color: ['#00AEEF', '#65B1FF'],
    xAxis: xAxis(category, true),
    yAxis: yAxis(max),
    grid: grid(),
    tooltip: tooltip(),
    series: series
  } as EChartsOption
}

function xAxis (data: Array<string>, boundaryGap?: boolean | Array<string>) {
  return {
    show: true,
    data: data,
    boundaryGap: boundaryGap || false
  } as XAXisOption
}

function yAxis (max:number) {
  const yAxis:YAXisOption = {
    show: true,
    axisLine: {
      show: true
    },
    axisTick: {
      show: false
    }
  }
  if (max) {
    yAxis.max = parseInt(String(max * 1.1))
  }
  return yAxis
}

function grid () {
  return {
    left: 0,
    right: 15,
    top: 20,
    bottom: 0,
    containLabel: true
  } as GridOption
}

function tooltip () {
  return {
    trigger: 'axis',
    confine: true,
    axisPointer: {
      textStyle: {
        color: '#fff'
      }
    }
  } as TooltipOption
}
